using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace MT5Trade.VerifyFileCacheCompliance
{
    /// <summary>
    /// 简化版文件缓存实现
    /// 用于验证缓存功能
    /// </summary>
    public class FileDataCache
    {
        private readonly string _cacheDirectory;
        private readonly ILogger<FileDataCache> _logger;
        private readonly TimeSpan _defaultExpiration;

        public FileDataCache(
            string cacheDirectory,
            ILogger<FileDataCache> logger,
            TimeSpan defaultExpiration)
        {
            _cacheDirectory = cacheDirectory;
            _logger = logger;
            _defaultExpiration = defaultExpiration;

            if (!Directory.Exists(_cacheDirectory))
            {
                Directory.CreateDirectory(_cacheDirectory);
            }
        }

        public async Task SaveHistoricalDataAsync(
            string symbol,
            DateTime startDate,
            DateTime endDate,
            Interval interval,
            List<MarketTick> data)
        {
            var key = GenerateCacheKey(symbol, startDate, endDate, interval);
            var filePath = Path.Combine(_cacheDirectory, $"{key}.json");

            var cacheData = new CacheData
            {
                Key = key,
                Symbol = symbol,
                StartDate = startDate,
                EndDate = endDate,
                Interval = interval.ToString(),
                Data = data,
                CreatedAt = DateTime.UtcNow,
                ExpiresAt = DateTime.UtcNow.Add(_defaultExpiration)
            };

            var json = JsonConvert.SerializeObject(cacheData, Formatting.Indented);
            await File.WriteAllTextAsync(filePath, json);

            _logger.LogInformation($"数据已缓存: {symbol}, 记录数: {data.Count}");
        }

        public async Task<List<MarketTick>> GetCachedHistoricalDataAsync(
            string symbol,
            DateTime startDate,
            DateTime endDate,
            Interval interval)
        {
            var key = GenerateCacheKey(symbol, startDate, endDate, interval);
            var filePath = Path.Combine(_cacheDirectory, $"{key}.json");

            if (!File.Exists(filePath))
            {
                return null;
            }

            var json = await File.ReadAllTextAsync(filePath);
            var cacheData = JsonConvert.DeserializeObject<CacheData>(json);

            // 检查过期
            if (cacheData.ExpiresAt < DateTime.UtcNow)
            {
                _logger.LogInformation($"缓存已过期: {symbol}");
                File.Delete(filePath);
                return null;
            }

            _logger.LogInformation($"从缓存加载数据: {symbol}, 记录数: {cacheData.Data.Count}");
            return cacheData.Data;
        }

        private string GenerateCacheKey(string symbol, DateTime startDate, DateTime endDate, Interval interval)
        {
            return $"{symbol}_{startDate:yyyyMMdd}_{endDate:yyyyMMdd}_{interval}";
        }

        public CacheStatistics GetStatistics()
        {
            var stats = new CacheStatistics
            {
                CacheDirectory = _cacheDirectory
            };

            if (Directory.Exists(_cacheDirectory))
            {
                var files = Directory.GetFiles(_cacheDirectory, "*.json");
                stats.TotalFiles = files.Length;

                long totalSize = 0;
                foreach (var file in files)
                {
                    var info = new FileInfo(file);
                    totalSize += info.Length;
                }

                stats.TotalSizeMB = totalSize / (1024.0m * 1024.0m);
                stats.ActiveFiles = stats.TotalFiles;
            }

            return stats;
        }

        private class CacheData
        {
            public string Key { get; set; }
            public string Symbol { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public string Interval { get; set; }
            public List<MarketTick> Data { get; set; }
            public DateTime CreatedAt { get; set; }
            public DateTime ExpiresAt { get; set; }
        }
    }

    public class CacheStatistics
    {
        public string CacheDirectory { get; set; }
        public int TotalFiles { get; set; }
        public int ActiveFiles { get; set; }
        public int ExpiredFiles { get; set; }
        public decimal TotalSizeMB { get; set; }
    }

    // 简化的实体类
    public class MarketDataTestEntity
    {
        public long Id { get; set; }
        public string Symbol { get; set; }
        public DateTime Time { get; set; }
        public decimal Open { get; set; }
        public decimal High { get; set; }
        public decimal Low { get; set; }
        public decimal Close { get; set; }
        public long Volume { get; set; }
        public string IntervalType { get; set; }
        public string DataSource { get; set; }
        public DateTime CreatedAt { get; set; }

        public MarketTick ToMarketTick()
        {
            return new MarketTick
            {
                Symbol = Symbol,
                Time = Time,
                Open = Open,
                High = High,
                Low = Low,
                Close = Close,
                Volume = Volume
            };
        }
    }

    public class MarketDataTestFilter
    {
        public string Symbol { get; set; }
        public DateTime? StartTime { get; set; }
        public DateTime? EndTime { get; set; }
        public string IntervalType { get; set; }
        public string DataSource { get; set; }
        public int? Limit { get; set; }
    }

    public class CachePerformanceTestEntity
    {
        public string TestName { get; set; }
        public string TestCaseId { get; set; }
        public string OperationType { get; set; }
        public int DataCount { get; set; }
        public decimal DurationMs { get; set; }
        public decimal? SpeedupRatio { get; set; }
    }
}